﻿using System;
using System.Collections.Generic;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

namespace belov_test
{
    public class ExcelManager
    {
        Excel.Application m_objExcel;
        Excel.Workbooks m_objBooks;
        Excel._Workbook m_objBook;
        Excel.Sheets m_objSheets;
        Excel._Worksheet m_objSheet;

        public ExcelManager()
        {
            CreateExcelInstance();
            InitObjects();
        }

        private void CreateExcelInstance()
        {
            m_objExcel = new Excel.Application();
        }

        private void InitObjects()
        {
            m_objBooks = (Excel.Workbooks) m_objExcel.Workbooks;
            m_objBook = (Excel._Workbook) m_objBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);

            m_objSheets = (Excel.Sheets) m_objExcel.Sheets;
            m_objSheet = (Excel._Worksheet) m_objSheets.get_Item(1);
        }

        public void SetCellValue(string row, string column, string value)
        {
            m_objSheet.Cells[row, column] = value;
        }

        public void SetRangeFontBoldProperty(string cell1, string cell2, bool value)
        {
            m_objSheet.get_Range(cell1, cell2).Font.Bold = value;
        }

        public void SetColumnsWidth(int width)
        {
            (m_objSheet.Cells as Excel.Range).ColumnWidth = width;
        }

        public void SetColumnWidth(string column, int width)
        {
            m_objSheet.get_Range(column, Type.Missing).ColumnWidth = width;
        }

        public void MergeCells(string cell1, string cell2)
        {
            m_objSheet.get_Range(cell1, cell2).Merge(Type.Missing);
        }

        public void SetRangeBottomLineWeight(string cell1, string cell2, int weight)
        {
            Excel.Border border = m_objSheet.get_Range(cell1, cell2).Borders[Excel.XlBordersIndex.xlEdgeBottom];
            border.Weight = weight;
        }

        public void SaveAs(string fileName)
        {
            m_objBook.SaveAs(
                fileName,
                m_objBook.FileFormat,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Excel.XlSaveAsAccessMode.xlShared,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing,
                Type.Missing
                );
        }

        public void CloseExcel()
        {
            m_objBook.Close(false, Type.Missing, Type.Missing);
            m_objExcel.Quit();
        }
    }
}
